<template>
    <FIModel v-model="visible" title="用户组选择" @close="closeClick" @confirm="saveFunc">
        <FISearchForm
            class="box-radius2"
            ref="ruleFormRef"
            :id="`inqu_${tableId}`"
            :searchNum="searchItemCount"
            :showCollapse="false"
            v-model:form-value="state.query"
            :table-column="columns"
            :wrapperSpan="8"
            @submit="searchFn"
        >
            <el-col :span="8">
                <FIFormItem prop="groupEname" label="用户组编码">
                    <FIInput v-model="state.query.groupEname" clearable />
                </FIFormItem>
            </el-col>
            <el-col :span="8">
                <FIFormItem prop="groupCname" label="用户组名称">
                    <FIInput v-model="state.query.groupCname" clearable />
                </FIFormItem>
            </el-col>
        </FISearchForm>
        <FITable
            ref="tableRef"
            class="box-radius2"
            title="用户组列表"
            :id="`result_${tableId}`"
            :data="dataList"
            primaryKey="formId"
            v-model:columns="columns"
            :showSaveModel="false"
            :isLoading="isTableLoading"
            :saveSuccessful="saveSuccessful"
            :pageConfig="pageConfig"
            :settingConfig="settingConfig"
            @table-refresh="searchFn"
            @selection-change="handleSelectionChange"
            @size-change="handleSizeChange"
            @current-page-change="handleCurrentChange"
        >
        </FITable>
    </FIModel>
</template>
  <script lang="ts" setup>
  import { reactive, onMounted, ref, computed, watch,toRaw } from 'vue'
  import FIFormItem from '@/components/FIFormItem.vue'
  import FIInput from '@/components/FIInput.vue'
  import FIForm from '@/components/FIForm.vue'
  import FIModel from '@/components/FIModel.vue'
  import { apiAuthMaintinsert ,apiGroupMaintquery} from '@/api/user'
  import { initSearchData } from '@/utils/common'
  import { useMessage} from '@/hooks/message'
  import type { PageConfig, Column } from '@/types/components'
  const emits = defineEmits(['close','update:usersShow','post-close'])
  const props = defineProps({
    // 圆角大小
    usersShow: {
      type: Boolean,
      default: false,
    },
    treeVal:{
      type: Array,
      default: ()=>[],
    },
    activeName:{
      type: String,
      default:'1'
    }
  })
  
  const state = reactive({
    query: {
      postCname:'',
      postEname:'',
      current: 1,
      size: 10,
    },
  })
  const dataList = ref([])
  const handleSizeChange = (e) => {
    pageConfig.pageSize = e
    pageConfig.currentPage = 1
    // searchFn()
  }
  const handleCurrentChange = (e) => {
    pageConfig.currentPage = e
    searchFn('page')
  }
  const isTableLoading = ref(false)
  // 保存成功按钮状态，默认不展示底部保存，取消按钮
  const saveSuccessful = ref(false)
  // 页面编码
  const tableId = 'pageMaint'
  const pageConfig: PageConfig = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100],
  })
  const columns: Column[] = reactive([
    {
      label: '用户组编码',
      prop: 'groupEname',
      align: 'center',
      editable: false,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '用户组名称',
      prop: 'groupCname',
      align: 'center',
      queryName: '',
      editable: false,
      sortable: true,
      filterable: false,
      readonly: true,
      
    },
    {
      label: '部门编码',
      prop: 'deptEname',
      queryName: 'tedfa00.form_Cname',
      align: 'center',
      editType: 'input',
      editable: false,
      filterable: false,
      sortable: false,
      sortValue: '',
     
    },
    {
      label: '部门名称',
      prop: 'deptCname',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
      editable: false,
      filterable: false,
      modelValue: { inputValue: '' },
      sortable: false,
      sortValue: '',
	  
    },
    {
      label: '岗位编码',
      prop: 'postEname',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
      editable: false,
      filterable: false,
      modelValue: { inputValue: '' },
      sortable: false,
      sortValue: '',
	  
    },
    {
      label: '岗位名称',
      prop: 'postCname',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
      editable: false,
      filterable: false,
      modelValue: { inputValue: '' },
      sortable: false,
      sortValue: '',
	  
    },
    
  ])
  const settingConfig = reactive({
    hidden: true, // 隐藏操作栏上所有内容
  })
  const checkedRows = ref([])
  const handleSelectionChange = (e) => {
    checkedRows.value = e
  }
  let visible: any = computed({
    get() {
        return props.usersShow
    },
    set(val) {
        emits('update:usersShow', val)
    },
    })
  // 隐藏搜索项有值的个数
  const searchItemCount = computed(() => {
    let filledCount = 0
    const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
    // 下面是从第三项起计算常规搜索条件有值个树
    // 获取state.query的所有keys
    const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
    if (queryKeys.length < 3) return 0
    // 从第三项开始计算
    queryKeys.slice(2).forEach((key) => {
      if (state.query[key] !== '' && state.query[key] !== null) {
        filledCount++
      }
    })
    return filledCount
  })
  const searchFn = (type?: string, columnsVal?: any,orgId?:any) => {
    const obj = initSearchData(type, columnsVal, columns, state.query)
    state.query = obj.queryData
    columns.values = obj.columns
    if(type == 'page'){
      state.query.current = pageConfig.currentPage
    }else{
      pageConfig.currentPage = 1
      state.query.current = 1
    }
    isTableLoading.value = true
    if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
    const par = {
      deptId:orgId || '',
      ...state.query,
    }
    apiGroupMaintquery(par)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          dataList.value = res.data.data.result
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        } else {
          // ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  const closeClick = () =>{
    emits('update:usersShow', false)
  }
  const saveFunc = () =>{
    console.log(props.treeVal,'树的数据')
    console.log(checkedRows.value,'岗位的数据')
    if(!checkedRows.value.length){
      useMessage().warning('请选一条数据')
      return;
    }
    let arr = [];
    props.treeVal.forEach(item1 => {
      checkedRows.value.forEach(item2 => {
        arr.push({
          resourceType:item1.payload.resourceType,
          resourceId: item1.payload.resourceId,
          subjectId: item2.groupId,
          subjectType: "USER_GROUP"
        });
      });
    });
    
    console.log(arr,'组装后的数据')
    // "resourceId": "e07cb5995bf848bb868639625ca434d2",
    // "resourceType": "BUTTON",
    // "subjectId": "34403687d254471992365b1fd1089e2e",
    // "subjectType": "USER_GROUP"
    apiAuthMaintinsert(arr)
    .then((res) => {
      if(res.data.success){
        useMessage().success(res.data.message)
        emits('update:usersShow', false)
        emits('post-close')
      }
    })
    .catch((error: any) => {
      
    })
  }
  onMounted(()=>{
    searchFn()
  })
  </script>
<style lang="less" scoped>
</style>
  